using Godot;
using Godot.Collections;

[Tool] // 允许在编辑器中运行，实现实时连线预览
public partial class ChromaButton : Area2D
{
    [ExportGroup("Logic")]
    [Export] public Array<ChromaDoor> TargetDoors = new Array<ChromaDoor>();

    // Reverse: false=踩下亮(金)松开灭(黑); true=踩下灭(黑)松开亮(金)
    [Export] public bool Reverse = false;

    [ExportGroup("Visuals")]
    [Export] public Sprite2D VisualSprite;
    [Export] public Node2D WireContainer; // 记得在场景里把 WireContainer 拖进来
    [Export] private float _wireWidth = 3.0f;
    // 电线颜色配置
    private Color _colorActive = new Color(2.0f, 1.5f, 0.2f); // 激活(亮金色)
    private Color _colorInactive = new Color(0.1f, 0.1f, 0.1f); // 未激活(深灰色)


    private int _pressingBodies = 0;

    public override void _Ready()
    {
        // 游戏运行时才连接信号
        if (!Engine.IsEditorHint())
        {
            BodyEntered += OnBodyEntered;
            BodyExited += OnBodyExited;
        }

        // 初始化绘制
        DrawWires();
        UpdateVisuals(false); // 初始状态为未按下
    }

    public override void _Process(double delta)
    {
        // 仅在编辑器模式下每帧重绘电线
        // 这样你在摆放关卡时，拖动门的位置，电线会自动跟随
        if (Engine.IsEditorHint())
        {
            DrawWires();
        }
    }

    // --- 核心逻辑 ---

    private void OnBodyEntered(Node2D body)
    {
        if (IsValidBody(body))
        {
            _pressingBodies++;
            UpdateLogic();
        }
    }

    private void OnBodyExited(Node2D body)
    {
        if (IsValidBody(body))
        {
            _pressingBodies--;
            if (_pressingBodies < 0) _pressingBodies = 0;
            UpdateLogic();
        }
    }

    private bool IsValidBody(Node2D body)
    {
        return body is PlayerController || body is ChromaBox;
    }

    private void UpdateLogic()
    {
        bool isPressed = _pressingBodies > 0;

        // 1. 按钮自身的视觉反馈 (按下变扁)
        UpdateVisuals(isPressed);

        // 2. 计算开门逻辑
        // 正常: 按下=Active(金), 门开
        // 反转: 按下=Inactive(黑), 门关
        bool isActive = Reverse ? !isPressed : isPressed;
        bool shouldOpen = isActive;

        // 3. 更新所有门的状态
        foreach (var door in TargetDoors)
        {
            if (door != null)
            {
                // door.SetOpenRequest(shouldOpen);
                door.ChangeState();
            }
        }

        // 4. 更新电线颜色 (金色/黑色)
        UpdateWireColors(isActive);
    }

    // --- 视觉绘制部分 ---

    private void UpdateVisuals(bool isPressed)
    {
        if (VisualSprite != null)
        {
            // 简单的按下动画 (Tween)
            var tween = CreateTween();
            float targetY = isPressed ? 0.5f : 1.0f;
            tween.TweenProperty(VisualSprite, "scale:y", targetY, 0.1f);

            // 按钮本体变色
            VisualSprite.Modulate = isPressed ? Colors.Green : Colors.White;
        }
    }

    // 生成“曼哈顿风格”的电线
    private void DrawWires()
    {
        if (WireContainer == null) return;

        // 1. 清空旧电线
        // 在 _Process 中频繁 Free 可能会有性能问题，但在编辑器模式下是可以接受的
        // 游戏运行时 DrawWires 只会在 _Ready 调一次，不会卡顿
        foreach (Node child in WireContainer.GetChildren())
        {
            child.QueueFree();
        }

        if (TargetDoors == null) return;

        // 2. 为每个门生成一根线
        foreach (var door in TargetDoors)
        {
            if (door == null) continue;

            // 获取门相对于按钮的局部坐标
            Vector2 targetLocalPos = ToLocal(door.GlobalPosition);

            // 创建 Line2D
            Line2D wire = new Line2D();
            wire.Width = _wireWidth;
            wire.DefaultColor = _colorInactive; // 默认为暗色
            wire.TextureMode = Line2D.LineTextureMode.None;
            wire.JointMode = Line2D.LineJointMode.Round;
            wire.BeginCapMode = Line2D.LineCapMode.Round;
            wire.EndCapMode = Line2D.LineCapMode.Round;

            // 计算曼哈顿路径点 (L型走线)
            // 路径：起点(0,0) -> 拐点 -> 终点
            // 拐点策略：先水平走，再垂直走
            Vector2 start = Vector2.Zero;
            Vector2 end = targetLocalPos;
            Vector2 corner = new Vector2(end.X, start.Y); // 拐点: (目标X, 起点Y)

            // 添加点
            wire.AddPoint(start);
            wire.AddPoint(corner);
            wire.AddPoint(end);

            WireContainer.AddChild(wire);
        }
    }

    private void UpdateWireColors(bool active)
    {
        if (WireContainer == null) return;

        Color targetColor = active ? _colorActive : _colorInactive;

        foreach (Node child in WireContainer.GetChildren())
        {
            if (child is Line2D wire)
            {
                // 使用 Tween 让颜色变化丝滑一点
                var tween = CreateTween();
                tween.TweenProperty(wire, "default_color", targetColor, 0.2f);
            }
        }
    }


    // public void ChangeState()
    // {
    //     UpdateLogic();
    // }
}